package me.yangbajing.web
package rest

import net.liftweb.http.rest.RestHelper
import net.liftweb.common.{Failure, Full, Loggable}
import net.liftweb.http.PlainTextResponse

import yangbajing.util.MarkdownHelpers
import me.yangbajing.model.{MDocument, MFavorite}

object DocumentRest extends RestHelper with Loggable {

  serve("api" / "document" prefix {
    case "markdown" :: "parser" :: Nil Post req =>
      try
        req.param("content") map
          (content => PlainTextResponse(MarkdownHelpers.parseToString(content))) or
          Full(PlainTextResponse("param content not found!"))
      catch {
        case e: Exception =>
          Full(PlainTextResponse(e.getLocalizedMessage))
      }

    case "favorite" :: "collect" :: Nil Post req =>
      logger.debug("params: " + req.params)
      for {
        docId <- req.param("doc_id")
        userId <- req.param("user_id")
      } yield MFavorite.insert(docId, userId) match {
        case Full(ret) =>
          MDocument.incrementFavoriteCount(docId)
          PlainTextResponse("SUCCESS")

        case Failure(msg, _, _) =>
          PlainTextResponse("收藏失败: " + msg)

        case _ =>
          PlainTextResponse("收藏失败")
      }

    case "favorite" :: "cancel" :: Nil Post req =>
      logger.debug("params: " + req.params)
      for {
        docId <- req.param("doc_id")
        userId <- req.param("user_id")
      } yield MFavorite.remove(docId, userId) match {
        case Full(1) =>
          MDocument.decrementFavoriteCount(docId)
          PlainTextResponse("SUCCESS")

        case Failure(msg, _, _) =>
          PlainTextResponse("取消收藏失败或者您本没有收藏过此文档: " + msg)

        case _ =>
          PlainTextResponse("取消收藏失败或者您本没有收藏过此文档")
      }
  })

}
